package com.zyk.scaffold.core.component;

import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * redis 令牌桶限流组件
 */
@Slf4j
public class RateRedisLimitComponent {

    private static final String REDIS_LIMIT_KEY = "limit:rate:";

    private StringRedisTemplate stringRedisTemplate;

    public RateRedisLimitComponent(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private DefaultRedisScript<List> redisScript = new DefaultRedisScript<>();

    {

        redisScript.setScriptSource(new ResourceScriptSource(
                new ClassPathResource("META-INF/scripts/rate-limiter.lua")));
        redisScript.setResultType(List.class);
    }

    /**
     * 获取key令牌，true 获取成功、false 获取失败
     *
     * @param key        识别key
     * @param replenishRate    每秒令牌增加量
     * @param burstCapacity    桶容量
     * @param requestedTokens  消耗令牌数量
     * @return boolean
     */
    public boolean tryAccess(String key, long replenishRate, long burstCapacity, long requestedTokens) {
        TokenInfos tokenInfos = requestedTokens(key, replenishRate, burstCapacity, requestedTokens);
        return tokenInfos.getAllowed();
    }

    /**
     * 获取key令牌
     *
     * @param key        识别key
     * @param replenishRate    每秒令牌增加量
     * @param burstCapacity    桶容量
     * @param requestedTokens  消耗令牌数量
     * @return TokenInfos
     */
    public TokenInfos requestedTokens(String key, long replenishRate, long burstCapacity, long requestedTokens) {
        List<String> keys = getKeys(key);
        List<String> scriptArgs = Arrays.asList(replenishRate + "", burstCapacity + "", Instant.now().getEpochSecond() + "", requestedTokens + "");
        List<Long> execute = new ArrayList<>();
        try {
            List redisScriptResult = stringRedisTemplate.execute(redisScript, keys, scriptArgs);
            if(redisScriptResult != null){
                execute.addAll(redisScriptResult);
            }
        }catch (Exception ex){
            execute.addAll(Arrays.asList(1L, -1L));
        }
        boolean allowed = execute.get(0) == 1L;
        Long tokensLeft = execute.get(1);
        return TokenInfos
                .builder()
                .allowed(allowed)
                .replenishRate(replenishRate)
                .burstCapacity(burstCapacity)
                .requestedTokens(requestedTokens)
                .tokensLeft(tokensLeft)
                .build();
    }

    static List<String> getKeys(String key) {
        String tokenKey = REDIS_LIMIT_KEY + "tokens:" + key;
        String timestampKey = REDIS_LIMIT_KEY + "timestamp:" + key;
        return Arrays.asList(tokenKey, timestampKey);
    }
    @Data
    @Builder
    public static class TokenInfos{
        /**
         * 是否允许
         */
        private Boolean allowed;
        /**
         * 每秒令牌增加量
         */
        private Long replenishRate;
        /**
         * 桶容量
         */
        private Long burstCapacity;
        /**
         * 消耗令牌数量
         */
        private Long requestedTokens;
        /**
         * 剩下的令牌
         */
        private Long tokensLeft;
    }
}
